package cn.edu.swu.book;

import cn.edu.swu.core.BasicServlet;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.Writer;
import java.sql.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = "/book/*")
public class BookController extends BasicServlet {

    private BookService bookService = null;

    public void init(ServletConfig config) {
        BookRepo repo = new BookRepo();
        bookService = new BookService();
        bookService.setRepo(repo);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.methodRoute(request,response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.methodRoute(request,response);
    }
    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        String uri=request.getRequestURI();
        String method=uri.substring(uri.lastIndexOf("/")+1);
        System.out.println(method);

       try {


           if (method.equals("list")) {
               this.list(request, response);
           } else if (method.equals("add")) {
               this.add(request, response);
           }else if (method.equals("delete")){
               this.delete(request,response);
           }else if (method.equals("edit")){
               this.edit(request,response);
           }else if (method.equals("update")){
               this.update(request,response);
           }else if (method.equals("search")){
               this.search(request,response);
           }
       }catch (SQLException | IOException e){
           throw new ServletException(e);
       }
    }


    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        try {
            List<Book> books = this.bookService.getAll();
            try (Writer writer = response.getWriter()) {
                String table = this.wrapTable(books);
                String page = this.wrapPage(table);
                writer.write(page);
            }


        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    public void add(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String memo = request.getParameter("memo");
        String publish = request.getParameter("publish");

        try {
            this.bookService.save(name, author, price,memo, publish);
        } catch (SQLException e) {
            throw new ServletException(e);
        }

        response.sendRedirect("./list");
    }


    private void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, SQLException {
        int id=Integer.parseInt(request.getParameter("id"));
        this.bookService.deleteById(id);
        response.sendRedirect("./list");
    }

    private void edit(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, SQLException {
        int id=Integer.parseInt(request.getParameter("id"));
        try {
            Book book=this.bookService.getById(id);
            try (Writer writer = response.getWriter()) {
                String form = this.wrapEditForm(book);
                String page = this.wrapPage(form);
                writer.write(page);
            }


        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        }

    }

    private void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, SQLException{
        int id = Integer.parseInt(request.getParameter("id"));
        String name = request.getParameter("name");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String memo = request.getParameter("memo");
        String publish = request.getParameter("publish");

        try {
            this.bookService.update(id, name, author, price, memo, publish);
        } catch (SQLException e) {
            throw new ServletException(e);
        }
        response.sendRedirect("./list");
    }

    private void search(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException, SQLException {
        String key = request.getParameter("key");
        try {
            List<Book> books = this.bookService.search(key);
            try (Writer writer = response.getWriter()) {
                String table = this.wrapTable(books);
                String page = this.wrapPage(table);
                writer.write(page);
            }


        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        }
    }


    private String wrapTable(List<Book> books) {
        StringBuilder sb = new StringBuilder();
        sb.append("<table class='bs'>\n");
        sb.append("<tr><th>编号</th><th>书名</th><th>作者</th><th>价格</th><th>描述</th><th>发行日期</th><th></th><th></th></tr>\n");
        for (Book book : books) {
            sb.append("<tr>");
            sb.append("<td class='center'>").append(book.getId()).append("</td>");
            sb.append("<td>").append(book.getName()).append("</td>");
            sb.append("<td class='center'>").append(book.getAuthor()).append("</td>");
            sb.append("<td class='center'>").append(book.getPrice()).append("</td>");
            sb.append("<td>").append(book.getMemo()).append("</td>");
            sb.append("<td class='center'>").append(book.getPublish()).append("</td>");
            sb.append("<td class='center'><a href='./delete?id=" + book.getId() + "'>删除</a></td>");
            sb.append("<td class='center'><a href='./edit?id=" + book.getId() + "'>修改</a></td>");
            sb.append("</tr>");
        }
        sb.append("</table>");
        return sb.toString();
    }

    private String wrapEditForm(Book book){
        StringBuilder sb= new StringBuilder();
        sb.append("<center><br>")
                .append("<form action=\"./update\" method=\"post\">")
                .append("<input type=\"hidden\" name=\"id\" value=\""+ book.getId()+"\"><br><br>")
                .append("书名:<input type=\"text\" name=\"name\" value=\""+ book.getName()+"\"><br><br>")
                .append("作者:<input type=\"text\" name=\"author\" value=\""+ book.getAuthor()+"\"><br><br>")
                .append("价格:<input type=\"text\" name=\"price\" value=\""+ book.getPrice()+"\"><br><br>")
                .append("备注:<input type=\"text\" name=\"memo\" value=\""+ book.getMemo()+"\"><br><br>")
                .append("日期:<input type=\"text\" name=\"publish\" value=\""+ book.getPublish()+"\"><br><br>")
                .append("<input type=\"submit\" name=\"submit\" value=\"更新图书\"/>")
                .append("</form>")
                .append("</center>");
                return sb.toString();

    }
}












